/*
 * @lc app=leetcode.cn id=129 lang=cpp
 *
 * [129] 求根节点到叶节点数字之和
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution
{
public:
  int ans = 0;

  int sumNumbers(TreeNode* root)
  {
    DFS(root, 0);
    return ans;
  }

  void DFS(TreeNode* root, int num)
  {
    if (root) { // root 非空
      num = num * 10 + root->val;
      // root 为叶节点
      if (root->left == nullptr && root->right == nullptr)
        ans += num;
      else {
        DFS(root->left, num);
        DFS(root->right, num);
      }
    }
  }
};
// @lc code=end
